import type { CardQueryParams, SearchConfigDealItem } from '/@/api/general/model/cardModel';
import type { DropdownItemOption } from 'vant/lib/dropdown-item/types';
import { SearchLogicTypeEnum, SearchStyleTypeEnum } from '/@/api/general/model/cardModel';
import { computed, defineComponent, unref } from 'vue';
import { useVModels } from '@vueuse/core';
import setting from '/@/settings/projectSetting';
import { includes } from 'lodash-es';
import { Button, ConfigProvider, Field, Popup } from 'vant';
import { useGeneralGameHooks } from '/@/views/general/hooks/useConfigs';

import('./BaseSearchPopup.less');
export default defineComponent({
  name: 'BaseSearchPopup',
  props: {
    show: {
      type: Boolean as PropType<boolean>,
      required: true,
      default: () => {
        return false;
      },
    },
    queryState: {
      type: Object as PropType<CardQueryParams>,
      required: true,
    },
    // 是否为组牌使用的筛选项
    isDeck: {
      type: Boolean as PropType<boolean>,
      default: () => {
        return false;
      },
    },
  },
  emits: ['openSeriesPopup', 'openCurrentAttrsPopup', 'update:show', 'pageRefresh'],
  setup(props, { emit }) {
    const { show } = useVModels(props, emit);

    const { gameSearchConfigData, gameConfigData } = useGeneralGameHooks(); // gameConfigData

    // 打开筛选系列浮层
    const openSeries = () => {
      emit('openSeriesPopup');
    };

    const seriesNums = computed(() => {
      const { queryState } = props;
      if (queryState.series_ids?.length) {
        return `已选系列(${queryState.series_ids?.length})`;
      }
      return '全部系列';
    });

    // 打开其他动态筛选浮层
    const openCurrentAttr = (currentAttr: SearchConfigDealItem) => {
      emit('openCurrentAttrsPopup', currentAttr);
    };
    // 其他动态属性的展示
    const otherAttrNums = (attrParams: SearchConfigDealItem) => {
      const { queryState } = props;
      if (queryState[attrParams.attr_key]?.length) {
        return `已选${attrParams.title}(${queryState[attrParams.attr_key]?.length})`;
      }
      return `全部${attrParams.title}`;
    };

    // 筛选
    const emptyClick = () => {
      const { queryState } = props;
      queryState.series_ids = [];
      const excludeKeyArr = ['game_id', 'page', 'size', 'name', 'series_ids'];
      for (const ketStr in queryState) {
        if (!includes(excludeKeyArr, ketStr)) {
          queryState[ketStr] = undefined;
        }
      }
      emit('pageRefresh');
    };

    const multipleClick = (item: DropdownItemOption, key: string) => {
      const { queryState } = props;
      const selectValue = item.value as string;
      !queryState[key] ? (queryState[key] = []) : null;
      const keyOptions = queryState[key];
      if (keyOptions.includes(selectValue)) {
        const index = keyOptions.indexOf(selectValue);
        keyOptions?.splice(index, 1);
      } else {
        keyOptions?.push(selectValue);
      }
      emit('pageRefresh');
    };

    const singleClick = (item: DropdownItemOption, key: string) => {
      const { queryState } = props;
      const selectValue = item.value as string;
      !queryState[key] ? (queryState[key] = []) : null;
      const keyOptions = queryState[key];
      if (keyOptions.includes(selectValue)) {
        const index = keyOptions.indexOf(selectValue);
        keyOptions?.splice(index, 1);
      } else {
        keyOptions.length = 0;
        keyOptions?.push(selectValue);
      }
      emit('pageRefresh');
    };

    // 生成筛选项
    const CustomFilterBox = () => {
      const { queryState } = props;
      const BoxArray: VueNode[] = [];
      for (const item of gameSearchConfigData) {
        if (item.search_style === SearchStyleTypeEnum.DrawerLayer) {
          BoxArray.push(
            <div class='filter-box'>
              <div class={'block text-black mb-20px flex items-center'}>
                <span class={'filter-title'}>{item.title}</span>
                <div class={'ml-md flex-1 border-b-1 border-gray-200 border-dashed'}></div>
              </div>
              <div
                class={`series-attrs-box inline-block align-middle ${
                  props.queryState[item.attr_key]?.length ? 'active' : ''
                }`}
                onClick={() => {
                  openCurrentAttr(item);
                }}
              >
                <span style={{ color: gameConfigData.game_color }}>{otherAttrNums(item)}</span>
              </div>
            </div>
          );
          continue;
        } else if (item.search_style === SearchStyleTypeEnum.Text) {
          BoxArray.push(
            <div class='filter-box'>
              <div class={'block text-black mb-20px flex items-center'}>
                <span class={'filter-title'}>{item.title}</span>
                <div class={'ml-md flex-1 border-b-1 border-gray-200 border-dashed'}></div>
              </div>
              <Field
                v-model={[queryState[item.attr_key]]}
                placeholder={`输入${item.title}`}
                clearable
                size={'normal'}
                onUpdate:modelValue={() => {
                  emit('pageRefresh');
                }}
              />
            </div>
          );
          continue;
        }
        const ItemArray: VueNode[] = [];
        const { mapping } = item;
        mapping.map((mapItem) => {
          const isActive = includes(queryState[item.attr_key], mapItem.value);
          // 如果是图片
          if (mapItem.icon) {
            ItemArray.push(
              <li
                class={['box-img-item', { active: isActive }]}
                onClick={() => {
                  item.search_logic === SearchLogicTypeEnum.NO
                    ? singleClick(mapItem, item.attr_key)
                    : multipleClick(mapItem, item.attr_key);
                }}
              >
                <img src={mapItem.icon} alt='' />
              </li>
            );
          } else {
            const borderColor = gameConfigData.game_color;
            let textColor = gameConfigData.game_color;
            let bgColor = 'transparent';
            if (isActive) {
              textColor = '#fff';
              bgColor = gameConfigData.game_color;
            }
            ItemArray.push(
              <li
                class={['box-item', { active: isActive }]}
                onClick={() => {
                  item.search_logic === SearchLogicTypeEnum.NO
                    ? singleClick(mapItem, item.attr_key)
                    : multipleClick(mapItem, item.attr_key);
                }}
                style={{ borderColor: borderColor, color: textColor, background: bgColor }}
              >
                <span>{mapItem.text}</span>
              </li>
            );
          }
        });

        BoxArray.push(
          <div class={'filter-box'}>
            <div class={'block text-black mb-20px flex items-center'}>
              <span class={'filter-title'}>{item.title}</span>
              <div class={'ml-md flex-1 border-b-1 border-gray-200 border-dashed'}></div>
            </div>
            <ul class={'box-list level-list flex flex-wrap'}>{ItemArray}</ul>
          </div>
        );
      }
      return <>{BoxArray}</>;
    };

    return () => (
      <Popup
        v-model={[show.value, 'show']}
        position={'right'}
        style={{ width: '76%', height: '100%', zIndex: setting.PageTitleZIndex - 2 }}
        overlayStyle={{ zIndex: setting.PageTitleZIndex - 2 }}
        class={'general-basequery-popup'}
        teleport={'body'}
      >
        <div class='search-container'>
          <div class='title'>
            <ConfigProvider
              themeVars={{
                buttonBorderWidth: 0,
                buttonDefaultColor: '#1380F0',
              }}
              class={'flex items-center'}
            >
              <span class={'text-[36px] font-bold mr-lg'}>条件筛选</span>

              <Button icon={'replay'} size={'mini'} class={'text-red-500'} onClick={emptyClick}>
                清空筛选项
              </Button>
            </ConfigProvider>
          </div>
          {gameConfigData.open_series_search ? (
            <div class='filter-box'>
              <div class={'block text-black mb-20px flex items-center'}>
                <span class={'filter-title'}>系列</span>
                <div class={'ml-md flex-1 border-b-1 border-gray-200 border-dashed'}></div>
              </div>
              <div
                class={`series-attrs-box inline-block align-middle ${
                  props.queryState.series_ids?.length ? 'active' : ''
                }`}
                onClick={openSeries}
              >
                <span style={{ color: gameConfigData.game_color }}>{unref(seriesNums)}</span>
              </div>
            </div>
          ) : null}
          <CustomFilterBox />
        </div>
      </Popup>
    );
  },
});
